
<?php
@session_start();
header("Content-Type: text/html;charset=utf-8");

include("lang/{$_SESSION['languaje']}.php");
include_once './db_conecta_adodb.inc.php';
include_once './function.inc.php';

$action=$_GET['action'];
$languaje=$_SESSION['languaje'];

//$db->debug=true;

switch ($action){
	case "check_availability":
		$checkin=$_GET['checkin'];
		$checkout=$_GET['checkout'];
		$guests=$_GET['guests'];
		if (isset($_GET['code']))
			$code=$_GET['code'];
		else
			$code=null;		

		//var_dump($_SESSION['languaje']);

		$checkin=generalizeDate($checkin,$_SESSION['languaje']);
		$checkout=generalizeDate($checkout,$_SESSION['languaje']);

		//Busco el maximo posible de ocupación
		$rs_ocup=sql("SELECT (SELECT CHR_VALUE FROM u172676809_fcac.T_PARAMETERS
						WHERE CHR_PARAMETER='MIN_OCUP') AS MIN_OCUP,
						(SELECT CHR_VALUE FROM u172676809_fcac.T_PARAMETERS
						WHERE CHR_PARAMETER='MAX_OCUP') AS MAX_OCUP
						FROM DUAL","");
		$ocup=siguiente($rs_ocup);
		$min_ocup=(int)$ocup->MIN_OCUP;
		$max_ocup=(int)$ocup->MAX_OCUP;
		if ($guests < $min_ocup){
			$return = array('html' => '',
						 	'msg' => $book_msg_capacity_min,
						 	'type' => 'e');
			break;
		}
		if ($guests > $max_ocup){
			$return = array('html' => '',
						 	'msg' => $book_msg_capacity,
						 	'type' => 'e');
			break;
		}
		//Verifico disponibilidad de ocupacion
		$cant=checkAvailability($checkin,$checkout,$code);
		
		if ($cant > 0){
			$return = array('html' => '',
						 	'msg' => $book_msg_no_av,
						 	'type' => 'e');
			break;
		}
		$return = array('html' => "<script>$('#step1').toggle(300);$('#step2').toggle(300);$('#inputName').focus();</script>",
						 'msg' => null,
						 'type' => null);
		break;

	case "ArmarComboPais":
		$id=$_GET['id'];
		$value=$_GET['value'];
		$table=$_GET['table'];
		$msgSelect=$_GET['msgSelect'];
		$name=$_GET['name'];
		$tabIndex=$_GET['tabindex'];

		$combo=armarComboSeleccione($table,$id,$value,$name,$msgSelect,null,false,$tabIndex);
		
		$return=array('html' => $combo,
						'msg' => null,
						'type' => null);
		break;

	case "returnDialCode":
		$id=$_GET['id'];
		
		if ($id==0){
			$code='';
		}else{
			$code=returnScalar('T_COUNTRIES','id_country',$id,'chr_dial_code');
			$code='+'.$code;
		}
		
		$return=array('html' => $code,
						'msg' => null,
						'type' => null);

		break;

	case "armarComboArrive":
		$name=$_GET['name'];
		$msgKnow=$_GET['msgKnow'];
		$msgNext=$_GET['msgNext'];
		$tabIndex=$_GET['tabindex'];
		
		$combo = '<select id ="'.$name.'" name="'.$name.'" class="form-control" tabindex="'.$tabIndex.'"><option value="-1">'.$msgKnow.'</option><option value="0">00:00 - 01:00</option><option value="1">01:00 - 02:00</option><option value="2">02:00 - 03:00</option><option value="3">03:00 - 04:00</option><option value="4">04:00 - 05:00</option><option value="5">05:00 - 06:00</option><option value="6">06:00 - 07:00</option><option value="7">07:00 - 08:00</option><option value="8">08:00 - 09:00</option><option value="9">09:00 - 10:00</option><option value="10">10:00 - 11:00</option><option value="11">11:00 - 12:00</option><option value="12">12:00 - 13:00</option><option value="13">13:00 - 14:00</option><option value="14">14:00 - 15:00</option><option value="15">15:00 - 16:00</option><option value="16">16:00 - 17:00</option><option value="17">17:00 - 18:00</option><option value="18">18:00 - 19:00</option><option value="19">19:00 - 20:00</option><option value="20">20:00 - 21:00</option><option value="21">21:00 - 22:00</option><option value="22">22:00 - 23:00</option><option value="23">23:00 - 00:00</option><option value="24">00:00 - 01:00 ('.$msgNext.')</option><option value="25">01:00 - 02:00 ('.$msgNext.')</option><option value="26">02:00 - 03:00 ('.$msgNext.')</option></select>';		
		
		$return = array('html' => $combo,'msg' => null,'type' => null);
		
		break;

	case "get_rate":
		$idCurrency=$_GET['inputCurrency'];
		$date_today=date("d-m-Y");

		//Precio actual y hasta precio actual
		$rs_price=sql("SELECT DCM_PRICE,dt_to from u172676809_fcac.T_PRICE_PERIOD 
						where dt_from <= STR_TO_DATE(?,'%d-%m-%Y')
						and dt_to >= STR_TO_DATE(?,'%d-%m-%Y')",array($date_today,$date_today));
		if(!is_null($rs_price)){
			$price_today=siguiente($rs_price);
			$today_price=$price_today->DCM_PRICE;
			$today_to=$price_today->DT_TO;
		}
		//Precio sguiente y hasta precio siguiente
		$rs_price_next=sql("SELECT DCM_PRICE,dt_to
							from u172676809_fcac.T_PRICE_PERIOD
							where dt_from <= adddate(STR_TO_DATE(?,'%Y-%m-%d'),interval 1 day)
							and dt_to >= adddate(STR_TO_DATE(?,'%Y-%m-%d'),interval 1 day)",array($today_to,$today_to));
		if(!is_null($rs_price_next)){
			$price_next=siguiente($rs_price_next);
			$next_price=$price_next->DCM_PRICE;
			$next_to=$price_next->DT_TO;
		}
		//Parametros de configuracion
		$rs_parameters=sql("SELECT CHR_PARAMETER,CHR_VALUE FROM u172676809_fcac.T_PARAMETERS","");
		if(!is_null($rs_parameters)){
			while ($parameters=siguiente($rs_parameters)){
				switch ($parameters->CHR_PARAMETER){
					case 'MIN_OCUP':
						$min_ocup=$parameters->CHR_VALUE;
						break;
					case 'MAX_OCUP':
						$max_ocup=$parameters->CHR_VALUE;
						break;
					case 'MONTO_ACT_PRECIO':
						$monto_act_precio=$parameters->CHR_VALUE;
						break;
					case 'BASE_PRECIO_OCUPACION':
						$base_precio_ocupacion=$parameters->CHR_VALUE;
						break;
					case 'INCREM_COTIZ_OFICIAL':
						$increm_cotiz_oficial=$parameters->CHR_VALUE;
					default:
						break;
				}
			}
		}
		//Modifico el precio en base a la cotizacion y tipo de moneda
		//Busco el apocope de la moneda
		$rs_currency=sql("SELECT CHR_VALUE FROM u172676809_fcac.T_CURRENCY where id_currency=?",array($idCurrency));
		if(!is_null($rs_currency)){
			$currency=siguiente($rs_currency);
			$valCurrency=$currency->CHR_VALUE;
		}
		//Tipo de cambio
		$rs_trade=sql("SELECT DCM_VALUE FROM u172676809_fcac.T_TRADE where id_currency=?",array($idCurrency));
		if (!is_null($rs_trade) && $rs_trade->RecordCount() > 0){ //Si encuentra la moneda es distinta a la moneda por defecto
			//Seteo el valor de cambio
			$trade=siguiente($rs_trade);
			$change=floatval($trade->DCM_VALUE);
		}else{
			$change=0;
		}


		//Armo la tabla de precios
		$result='';
		for($i=$min_ocup;$i<=$max_ocup;$i++){
			$result.='<div class="row">';
			// Se agrega a pedido de Romina 07/09/2014
			if ($i==2)
				$result.='<div class="col-xs-6"><p class="rates-guest">'.$book_rates_12.' '.$book_guests.'</p></div>';
			else
				$result.='<div class="col-xs-6"><p class="rates-guest">'.$i.' '.$book_guests.'</p></div>';
			// Si la moneda es dolar no incremento el tipo de cambio
			// Formula del calculo: Cantidad de ocupantes por monto de actualizacion del precio por huesped
			// + precio de ocupacion estandar por el tipo de cambio por el porcentaje de actualizacion de tipo de cambio
			if ($change==0)
				$rate=round(((($i- (int)$min_ocup)*(int)$monto_act_precio)+$today_price),0);
			else
				$rate=round(((($i- (int)$min_ocup)*(int)$monto_act_precio)+$today_price)*($change*(1+(floatval($increm_cotiz_oficial)/100))),0);
			$result.='<div class="col-xs-6"><p class="rates-price">'.$valCurrency.' '.$rate.'</p></div>';
			$result.='</div>';
		}
		$today_to=convertDate($today_to,$languaje);
		$result.='<div class="row"><p class="rates-note"><img src="../img/info.png" class="img-info"/>  '.$book_rates_note.' '.$today_to.'. '.$book_rates_note_2.'</p></div>';

		$return = array('html' => $result,
					 	'msg' => '',
		 				'type' => '');
		break;

	case "ArmarComboMoneda":
		$id=$_GET['id'];
		$value=$_GET['value'];
		$table=$_GET['table'];
		$name=$_GET['name'];
		$puntero=$_GET['puntero'];

		if (isset($_GET['disable']))
			$disable=$_GET['disable'];
		else
			$disable=0;

		if ($disable==1)
			$disable=true;
		else
			$disable=false;

		$combo=armarComboPuntero($table,$id,$value,$name,$puntero,$disable,null);
		
		//$combo=(string)$combo;
		//echo $combo;

		//$combo="<select  id ='inputCurrency' name='inputCurrency' class='form-control' tabindex=''><option value='3'>US$ - Dolar Estadounidense</option><option value='4'>$(ARS) - Peso Argentino</option><option value='5'>€ - Euro</option></select>";

		$return = array('html' => $combo,
					 	'msg' => '',
		 				'type' => '');
		break;

	case "ShowConfirmBook":
		$checkin=$_GET['checkin'];
		$checkout=$_GET['checkout'];
		$guests=$_GET['guests'];
		$name=$_GET['inputName'];
		$lastName=$_GET['inputLastName'];
		$idCountry=$_GET['inputCountry'];
		$email=$_GET['inputEmail'];
		$confirEmail=$_GET['inputConfirmEmail'];
		$phone=$_GET['inputPhone'];
		$optPhone=$_GET['inputOptPhone'];
		$arrive=$_GET['inputArrive'];
		$request=$_GET['inputRequest'];

		$checkin=generalizeDate($checkin,$_SESSION['languaje']);
		$checkout=generalizeDate($checkout,$_SESSION['languaje']);
		$days=cantDays(date($checkin),date($checkout));

		$checkin = formatDateLong($checkin,$_SESSION['languaje']);
		$checkout = formatDateLong($checkout,$_SESSION['languaje']);


		//busco el pais
		$rs_country=sql("SELECT chr_name_".$languaje." AS NAME FROM u172676809_fcac.T_COUNTRIES where ID_COUNTRY=?",array($idCountry));
		if(!is_null($rs_country)){
			$countryRow=siguiente($rs_country);
			$countryName=$countryRow->NAME;
		}
		$table='<div class="row"><h3>'.$book_confirm_reservation.'</h3></div>';
		$table.='<div class="row"><div class="col-xs-9"><p class="no-margin">'.$book_check_in.': '.$checkin.'</p></div><div class="col-xs-3"><p class="no-margin">'.$book_confirm_days.': '.$days.'</p></div></div>';
		$table.='<div class="row"><div class="col-xs-12"><p class="no-margin">'.$book_check_out.': '.$checkout.'</p></div></div>';
		$table.='<div class="row"><div class="col-xs-4"><p class="no-margin">'.$book_guests.': '.$guests.'</p></div><div class="col-xs-8"><p class="no-margin">'.$book_data_arrive.': '.$arrive.'</p></div></div>';
		$table.='<div class="row"><div class="col-xs-12"><p class="no-margin">'.$book_data_request.': '.$request.'</p></div></div>';
		$table.='<div class="row"><h3>'.$book_confirm_contact.'</h3></div>';
		$table.='<div class="row"><div class="col-xs-6"><p class="no-margin">'.$book_data_name.': '.$name.'</p></div><div class="col-xs-6"><p class="no-margin">'.$book_data_last_name.': '.$lastName.'</p></div></div>';
		$table.='<div class="row"><div class="col-xs-6"><p class="no-margin">'.$book_data_email.': '.$email.'</p></div><div class="col-xs-6"><p class="no-margin">'.$book_data_country.': '.$countryName.'</p></div></div>';
		$table.='<div class="row"><div class="col-xs-6"><p class="no-margin">'.$book_data_phone.': '.$phone.'</p></div><div class="col-xs-6"><p class="no-margin">'.$book_data_opt_phone.': '.$optPhone.'</p></div></div>';
		
		$return=array('html' => $table,
						'msg' => null,
						'type' => null);
		break;

	case "verifBookingData":
		$name=$_GET['inputName'];
		$lastName=$_GET['inputLastName'];
		$idCountry=$_GET['inputCountry'];
		$email=$_GET['inputEmail'];
		$confirmEmail=$_GET['inputConfirmEmail'];
		$phone=$_GET['inputPhone'];

		if (!validChrField($name,2)){               
        $return=array('html' => "<script>$('#inputName').focus();</script>",
                      'msg' => $book_msg_data_name,
                      'type' => 'a');
        	break;
	    }
	    if (!validChrField($lastName,2)){
	        $return=array('html' => "<script>$('#inputLastName').focus();</script>",
	                        'msg' => $book_msg_data_lastname,
	                        'type' => 'a');
	        break;
	    }
	    if ($idCountry <= '0'){
	        $return=array('html' => "<script>$('#inputCountry').focus();</script>",
	                        'msg' => $book_msg_data_country,
	                        'type' => 'a');
	        break;
	    }
	    if (!validMailField($email)){
	        $return=array('html' => "<script>$('#inputEmail').focus();</script>",
	                        'msg' => $book_msg_data_mail,
	                        'type' => 'a');
	        break;
	    }
	    if (!validMailField($confirmEmail)){
	        $return=array('html' => "<script>$('#inputConfirmEmail').focus();</script>",
	                        'msg' => $book_msg_data_conf_mail,
	                        'type' => 'a');
	        break;
	    }
	    if ($email != $confirmEmail){
	        $return=array('html' => "<script>$('#inputConfirmEmail').focus();</script>",
	                        'msg' => $book_msg_data_mail_match,
	                        'type' => 'a');
	        break;
	    }
	    if (!validChrField($phone,5)){
	        $return=array('html' => "<script>$('#inputName').focus();</script>",
	                        'msg' => $book_msg_data_phone,
	                        'type' => 'a');
	        break;
	    }

		$return=array('html' => "",
						'msg' => "",
						'type' => "");
		break;

	case "ConfirmBook":
		$checkin=$_GET['checkin'];
		$checkout=$_GET['checkout'];
		$guests=$_GET['guests'];
		$name=$_GET['inputName'];
		$lastName=$_GET['inputLastName'];
		$idCountry=$_GET['inputCountry'];
		$email=$_GET['inputEmail'];
		$phone=$_GET['inputPhone'];
		$optPhone=$_GET['inputOptPhone'];
		$arrive=$_GET['arrive'];
		$arriveValue=$_GET['inputArrive'];
		$request=$_GET['inputRequest'];
		$idCurrency=$_GET['inputCurrency'];
		$checkin=generalizeDate($checkin,$_SESSION['languaje']);
		$checkout=generalizeDate($checkout,$_SESSION['languaje']);
		
		//Genero codigo de reserva
		$rs_code=sql("SELECT UPPER(SUBSTRING(MD5(RAND()) FROM 1 FOR 6)) AS CODE from dual","");
		$reg=siguiente($rs_code);
		$code=$reg->CODE;
		$code=strtoupper($code);

		//Calculo precios
		$pricing=calcPrice($checkin,$checkout,$guests,$idCurrency);
		$price = $pricing['price'];
    	$vat = $pricing['iva'];
    	$total = $pricing['final'];
    	$valCurrency = $pricing['currency'];

		//Fecha de Vencimiento de la reserva
		$rs_fec_venc=sql("SELECT CHR_VALUE AS HS_VENC 
						FROM u172676809_fcac.T_PARAMETERS 
						WHERE CHR_PARAMETER='HORAS_VENC_RESERVA'","");
		$row=siguiente($rs_fec_venc);
		$hs_venc=(int)$row->HS_VENC;

		$hoy = date('Y-m-d');
		$expDate = date('Y-m-d',strtotime('+'.$hs_venc.' hour',strtotime($hoy)));

		//Calulo la cantidad de días de la reserva
		$days=cantDays(date($checkin),date($checkout));

		//Inserto el registro
		try{
			sql("INSERT INTO `u172676809_fcac`.`T_BOOKS`
				(`DT_CHECK_IN`,
				`DT_CHECK_OUT`,
				`INT_GUESTS`,
				`CHR_NAME`,
				`CHR_LAST_NAME`,
				`FK_ID_COUNTRY`,
				`CHR_EMAIL`,
				`CHR_PHONE`,
				`CHR_OPT_PHONE`,
				`CHR_ARRIVE`,
				`CHR_REQUEST`,
				`CHR_BOOK_CODE`,
				`DT_ENTRY`,
				`DCM_PRICE`,
				`DCM_VAT`,
				`DCM_TOTAL`,
				`ID_CURRENCY`,
				`DT_EXPIRATION_DATE`,
				`INT_DAYS`,
				`INT_ARRIVE_VALUE`
				)
				VALUES
				(STR_TO_DATE(?,'%d-%m-%Y'),STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,?,STR_TO_DATE(?,'%Y-%m-%d'),?,?,?,?,?,?)",
				array($checkin,$checkout,$guests,$name,$lastName,$idCountry,$email,$phone,$optPhone,$arrive,$request,$code,date('Y-m-d'),(int)$price,$vat,$total,$idCurrency,$expDate,$days,$arriveValue));
		}catch (exception $e){
			$return=array('html' => '',
						'msg' => 'DB Error - '.$e,
						'type' => 'e');
			break;
		}
		/*try{
			$rs_conf = sql("SELECT u172676809_fcac.FN_CONFIRM_BOOK(STR_TO_DATE(?,'%d-%m-%Y'),STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,?,?,?) AS MSG FROM DUAL",array($checkin,$checkout,$guests,$name,$lastName,$idCountry,$email,$phone,$optPhone,$arrive,$request,$idCurrency,$arriveValue,null,'INS'));

			while($row = siguiente($rs_conf))
		    		$msgText = $row->MSG;
		}catch(exception $e){
		   	$msgText = 'db error';
		}*/

		/*$pos_sep = strpos($msgText, '-');
		$len_type = $pos_sep;
		$type = substr($msgText,0,$len_type);
		$len = strlen($msgText);
		$len_msg = $len - $pos_sep;
		$msg = substr($msgText,$pos_sep+1,$len_msg);*/

		//var_dump($type);
		//var_dump($msg);

		/*if ($type=='ok'){//Correcto

			$rs_book=sql("SELECT CHR_BOOK_CODE AS CODE, DT_EXPIRATION_DATE AS EXPIRATION, DCM_TOTAL AS TOTAL, CHR_VALUE AS CURRENCY, INT_DAYS AS DAYS FROM u172676809_fcac.T_BOOKS B, u172676809_fcac.T_CURRENCY C WHERE INT_ID_BOOK=? AND B.ID_CURRENCY=C.ID_CURRENCY",array($msg));
			while($row = siguiente($rs_book)) {
		    	$code = $row->CODE;
		    	$expDate = $row->EXPIRATION;
		    	$total = $row->TOTAL;
		    	$valCurrency = $row->CURRENCY;
		    	$days = $row->DAYS;}*/

		    $expDate = formatDateLong($expDate,$_SESSION['languaje']);
		    $checkin = formatDateLong($checkin,$_SESSION['languaje']);
			$checkout = formatDateLong($checkout,$_SESSION['languaje']);
		    
		    //Enviar mail usuario
			$body = '<tr><td style="padding:5px;font-size:20px;font-family:Candara,Calibri,Arial,sans-serif;color:#FFD700;">'.$mail_dear.' '.$name.':'.'</td></tr>';
			$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_mail_line1.'</td></tr>';
			$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_mail_line2.'</td></tr>';
			$body.= '<tr><td><table border="1" rules="all" width="80%" align="center">';
			$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_check_in.': '.$checkin.'</td><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_confirm_days.': '.$days.'</td></tr>';
			$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_check_out.': '.$checkout.'</td><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_guests.': '.$guests.'</td></tr>';
			$body.= '<tr><td colspan="2" style="padding:5px;font-size:18px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;text-align:center;">'.$book_confirm_total.': '.$valCurrency.' '.$total.'.-</td></tr>';
			$body.= '</table></td></tr>';
			$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_mail_line3.'<span style="padding:5px;font-size:22px;font-family:Candara,Calibri,Arial,sans-serif;color:#FFD700;">'.$code.'</span>'.$book_mail_line4.'.</td></tr>';
			$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_mail_line6.$expDate.$book_mail_line7.'</td></tr>';
			$body.= '<tr><td><hr></td></tr>';
			$body.= '<tr><td style="padding:1px;font-size:10px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;"><em>'.$book_mail_foot.'</em></td></tr>';

			/*$body ='<table width="100%" border="0" cellspacing="0" cellpadding="0">';
			$body ='<tr style="background-image: linear-gradient(to bottom,#FFFFFF 0,#FFD700 150%);"><td align="center" style="padding:0.5em"><img src="http://firstclassapartment.com.ar/public/img/head_mail.png"/></td></tr>';
		    $body ='<table width="100%" style="border-color: #FFD700;border-style: ridge;border-width: 3px;background-image: linear-gradient(to bottom,#1d1d1d 0,#222 100%);padding: 1em; border-top:none;">';

		    $body.='<h1 class="mail">'.$mail_dear.' '.$name.':'.'</h1>';
			$body.='<p>'.$book_mail_line1.'</p>';
			$body.='<p>'.$book_mail_line2.'</p>';
			$body.='<table class="table table-bordered"><tr><td>'.$book_check_in.': '.$checkin.'</td><td>'.$book_confirm_days.': '.$days.'</td></tr>';
			$body.='<tr><td>'.$book_check_out.': '.$checkout.'</td><td>'.$book_guests.': '.$guests.'</td></tr>';
			$body.='<tr><td colspan="2">'.$book_confirm_total.': '.$valCurrency.' '.$total.'</td></tr></table>';
			$body.='<p>'.$book_mail_line3. '<span class="p-mail-code">'.$code.'</span>'.$book_mail_line4.$book_mail_line5.'</p>';
			$body.='<p>'.$book_mail_line6.$expDate.$book_mail_line7.'</p>';
			$body.='<hr>';
			$body.='<p class="mail-foot">'.$book_mail_foot.'</p>';*/

		    sendMail($email,'book',$book_mail_subject,$body);

		    //Enviar mail FCAC
		    //Enviar mail a contacto
			$body = '<tr><td style="padding:5px;font-size:20px;font-family:Candara,Calibri,Arial,sans-serif;color:#FFD700;">Se ha registrado una nueva reserva.</td></tr>';
			sendMail('booking@firstclassapartment.com.ar','book','Nueva Reserva',$body);
			$return=array('html' => "<script>showMsg('confirmation1','".$book_msg_conf_1.$code.$book_msg_conf_2."','o');showMsg('confirmation2','".$book_msg_conf_3.$expDate.$book_msg_conf_4."','i');</script>",
						'msg' => '',
						'type' => '');
		/*}else{//Error
			$return=array('html' => "",
						'msg' => ${$msg},
						'type' => 'e');
		}*/
			setSysNew('i','Se ha registrado una nueva reserva. Código de Reserva: '.$code);

		break;

	case "calcPrice":
		$checkin=$_GET['checkin'];
		$checkout=$_GET['checkout'];
		$guests=$_GET['guests'];
		$idCurrency=$_GET['inputCurrency'];
		$checkin=generalizeDate($checkin,$_SESSION['languaje']);
		$checkout=generalizeDate($checkout,$_SESSION['languaje']);

		/*$rs = sql("SELECT u172676809_fcac.FN_CALC_PRICE(STR_TO_DATE(?,'%d-%m-%Y'),STR_TO_DATE(?,'%d-%m-%Y'),?,?) AS RESULT FROM DUAL",array($checkin,$checkout,$guests,$idCurrency));

		while($row=siguiente($rs)){
			$result=$row->RESULT;
		}

		//var_dump($result);

		$inicio_price = 0;
		$pos_sep_price = strpos($result, '-');
		$lenght_price=$pos_sep_price-$inicio_price;
		$price = substr($result,$inicio_price,$lenght_price);

		$inicio_vat=$pos_sep_price+1;
		$pos_sep_vat=strpos($result, '-',$inicio_vat);
		$lenght_vat=$pos_sep_vat-$inicio_vat;
		$vat = substr($result,$inicio_vat,$lenght_vat);

		$inicio_total=$pos_sep_vat+1;
		$pos_sep_total=strpos($result, '-',$inicio_total);
		$lenght_total=$pos_sep_total-$inicio_total;
		$total = substr($result,$inicio_total,$lenght_total);

		$inicio_curr=$pos_sep_total+1;
		$pos_sep_curr=strlen($result);
		$lenght_curr=$pos_sep_curr-$inicio_curr;
		$valCurrency = substr($result,$inicio_curr,$lenght_curr);*/

		$pricing=calcPrice($checkin,$checkout,$guests,$idCurrency);
		$price = $pricing['price'];
    	$vat = $pricing['iva'];
    	$total = $pricing['final'];
    	$valCurrency = $pricing['currency'];

		$table='<div class="row"><h3>'.$book_confirm_price.'</h3></div>';
		$table.='<div class="row"><div class="col-xs-5 left no-padding"><p class="rates-guest">'.$book_confirm_total_price.'</p></div><div class="col-xs-7 right no-padding"><p id="price" class="rates-guest right">'.$valCurrency.' '.$price.'</p></div></div>';
		$table.='<div class="row"><div class="col-xs-5 left no-padding"><p class="rates-guest">'.$book_confirm_iva.'</p></div><div class="col-xs-7 right no-padding"><p id="vat" class="rates-guest right">'.$valCurrency.' '.$vat.'</p></div></div>';
		$table.='<div class="row"><div class="col-xs-5 col-xs-offset-7 no-padding" style="height: 1.1em "><hr></div></div>';
		$table.='<div class="row"><div class="col-xs-5 left no-padding"><p class="rates-guest">'.$book_confirm_total.'</p></div><div class="col-xs-7 right no-padding"><p id="total" class="rates-guest right">'.$valCurrency.' '.$total.'</p></div></div>';

		$return=array('html' => $table,
						'msg' => null,
						'type' => null);

		break;

	case 'validateContact':
		$name=$_GET['inputName'];
		$lastName=$_GET['inputLastName'];
		$idCountry=$_GET['inputCountry'];
		$email=$_GET['inputEmail'];
		$phone=$_GET['inputPhone'];
		$question=$_GET['inputQuestion'];
		$recaptcha_response_field=$_GET['recaptcha_response_field'];
		$recaptcha_challenge_field=$_GET['recaptcha_challenge_field'];
		
		include_once('recaptchalib.php');
		$private_key='6LfoDfYSAAAAAHt0YLMfac4GaCvhkZPiaRY8SFyU';
		$resp = recaptcha_check_answer ($private_key,
                                $_SERVER["REMOTE_ADDR"],
                                $recaptcha_challenge_field,
                                $recaptcha_response_field);
		//var_dump($resp);
		if (!$resp->is_valid) {
		    $return=array('html' => '',
							'msg' => $locont_contact_msg_captcha,
							'type' => 'a');
		    break;
		}

		if (!validChrField($name,2)){               
	        $return=array('html' => '',
							'msg' => $book_msg_data_name,
							'type' => 'a');
        	break;
	    }
	    if (!validChrField($lastName,2)){
	        $return=array('html' => '',
	                        'msg' => $book_msg_data_lastname,
	                        'type' => 'a');
	        break;
	    }
	    if ($idCountry <= '0'){
	        $return=array('html' => '',
	                        'msg' => $book_msg_data_country,
	                        'type' => 'a');
	        break;
	    }
	    if (!validMailField($email)){
	        $return=array('html' => '',
	                        'msg' => $book_msg_data_mail,
	                        'type' => 'a');
	        break;
	    }
	    if ($phone<>''){
		    if (!validChrField($phone,5)){
		        $return=array('html' => "<script>$('#inputName').focus();</script>",
		                        'msg' => $book_msg_data_phone,
		                        'type' => 'a');
		        break;
		    }
		}
		if (!validChrField($question,5)){
			$return=array('html' => '',
							'msg' => $locont_contact_msg_question,
							'type' => 'a');
			break;
		}

		//busco el pais
		$rs_country=sql("SELECT chr_name_".$languaje." AS NAME FROM u172676809_fcac.T_COUNTRIES where ID_COUNTRY=?",array($idCountry));
		if(!is_null($rs_country)){
			$countryRow=siguiente($rs_country);
			$countryName=$countryRow->NAME;
		}

		//Enviar mail a usuario
		$body = '<tr><td style="padding:5px;font-size:20px;font-family:Candara,Calibri,Arial,sans-serif;color:#FFD700;">'.$mail_dear.' '.$name.':'.'</td></tr>';
		$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$locont_contact_usr_mail_line1.'</td></tr>';
		$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$locont_contact_usr_mail_line2.'</td></tr>';
		$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$locont_contact_usr_mail_line3.'</td></tr>';

		$body.= '<tr><td><hr></td></tr>';
		$body.= '<tr><td style="padding:1px;font-size:10px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;"><em>'.$book_mail_foot.'</em></td></tr>';
		sendMail($email,'contact',$locont_contact_usr_subject,$body);

		//Enviar mail a contacto
		$body = '<tr><td style="padding:5px;font-size:20px;font-family:Candara,Calibri,Arial,sans-serif;color:#FFD700;">'.$locont_contact_question.':'.'</td></tr>';
		$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$question.'</td></tr>';
		$body.= '<tr><td><table border="1" rules="all" width="80%" align="center">';
		$body.= '<tr><td colspan="2" style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_data_name.': '.$name.'</td></tr>';
		$body.= '<tr><td colspan="2" style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_data_last_name.': '.$lastName.'</td></tr>';
		$body.= '<tr><td colspan="2" style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_data_country.': '.$countryName.'</td></tr>';
		$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_data_email.': '.$email.'</td><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_data_phone.': '.$phone.'</td></tr>';
		$body.= '</table></td></tr>';
		sendMail('info@firstclassapartment.com.ar','contact',$locont_contact_info_subject,$body);

		$return=array('html' => "<script>$('#form-data').toggle(300);</script>",
						'msg' => $locont_contact_msg_ok,
						'type' => 'o');

		break;

	case 'getBookingData':
		$code=$_GET['inputCode'];
		$rs=sql("SELECT `T_BOOKS`.`DT_CHECK_IN` AS CHECK_IN,
					    `T_BOOKS`.`DT_CHECK_OUT` AS CHECK_OUT,
					    `T_BOOKS`.`INT_GUESTS` AS GUESTS,
					    `T_BOOKS`.`CHR_NAME` AS NAME,
					    `T_BOOKS`.`CHR_LAST_NAME` AS LAST_NAME,
					    `T_BOOKS`.`FK_ID_COUNTRY` AS ID_COUNTRY,
					    `T_BOOKS`.`CHR_EMAIL` AS EMAIL,
					    `T_BOOKS`.`CHR_PHONE` AS PHONE,
					    `T_BOOKS`.`CHR_OPT_PHONE` AS OPT_PHONE,
					    `T_BOOKS`.`CHR_ARRIVE` AS ARRIVE,
					    `T_BOOKS`.`CHR_REQUEST` AS REQUEST,
					    `T_BOOKS`.`DCM_PRICE` AS PRICE,
					    `T_BOOKS`.`DCM_VAT` AS VAT,
					    `T_BOOKS`.`DCM_TOTAL` AS TOTAL,
					    `T_BOOKS`.`ID_CURRENCY` AS ID_CURRENCY,
					    `T_BOOKS`.`DT_EXPIRATION_DATE` AS EXPIRATION_DATE,
					    `T_BOOKS`.`INT_DEPOSIT` AS DEPOSIT,
					    `T_BOOKS`.`INT_ARRIVE_VALUE` AS ARRIVE_VALUE,
					    `T_BOOKS`.`INT_CANCEL` AS CANCEL,
					    `T_BOOKS`.`DT_CANCEL` AS DT_CANCEL,
					    `T_BOOKS`.`INT_TOT_PAY` AS INT_TOT_PAY
				FROM `u172676809_fcac`.`T_BOOKS`
				WHERE CHR_BOOK_CODE=?",array($code));
		
		$count=sql("SELECT FOUND_ROWS() as CANT","");
		$cant=siguiente($count);

		if($cant->CANT > 0){
			$book=siguiente($rs);
			$checkin=date($book->CHECK_IN);
			$checkout=date($book->CHECK_OUT);
			$guests=$book->GUESTS;
			$name=$book->NAME;
			$lastName=$book->LAST_NAME;
			$idCountry=$book->ID_COUNTRY;
			$email=$book->EMAIL;
			$phone=$book->PHONE;
			$optPhone=$book->OPT_PHONE;
			$arrive=$book->ARRIVE;
			$request=$book->REQUEST;
			$price=(int)$book->PRICE;
			$vat=$book->VAT;
			$total=$book->TOTAL;
			$idCurrency=$book->ID_CURRENCY;
			$expirationDate=date($book->EXPIRATION_DATE);
			$deposit=$book->DEPOSIT;
			$arriveValue=$book->ARRIVE_VALUE;
			$cancel=$book->CANCEL;
			$cancelDate=$book->DT_CANCEL;
			$totPay=$book->INT_TOT_PAY;

			//Busca el estado de la reserva
			$array=getEstado($checkout,$cancel,$cancelDate,$expirationDate,$deposit,$totPay);
			$estado=$array['estado'];
			//var_dump($estado);

			if ($estado=='cancelada' || $estado=='vencida' || $estado=='liquidada'){
				switch($estado){
					case 'cancelada'://Verifico que no haya sido cancelada
						$return=array('html' => "",
							'msg' => $book_updbooking_msg_cancel,
							'type' => 'e');
						break;
					case 'vencida':// Verifico que no este vencida
						$return=array('html' => "",
							'msg' => $book_updbooking_msg_expire,
							'type' => 'e');
						break;
					case 'liquidada': //Verifico si ya está liquidada
						$return=array('html' => "",
							'msg' => $book_updbooking_msg_liquidada,
							'type' => 'o');
						break;
				}
				break;
			}

			//busco el valor de la moneda
			$rs_currency=sql("SELECT CHR_VALUE FROM u172676809_fcac.T_CURRENCY where id_currency=?",array($idCurrency));
			if(!is_null($rs_currency)){
				$currency=siguiente($rs_currency);
				$valCurrency=$currency->CHR_VALUE;
			}


			$checkin= dateFromDBtoPick($checkin,$_SESSION['languaje']);
			$checkout= dateFromDBtoPick($checkout,$_SESSION['languaje']);
			$return=array('html' => "<script>$('#checkin').val('".$checkin."');$('#checkout').val('".$checkout."');$('#inputName').val('".$name."');$('#inputLastName').val('".$lastName."');$('#guests').val(".$guests.");$('#inputCountry').val(".$idCountry.");$('#inputCountry').change();$('#inputEmail').val('".$email."');$('#inputConfirmEmail').val('".$email."');$('#inputPhone').val('".$phone."');$('#inputOptPhone').val('".$optPhone."');$('#inputArrive').val(".$arriveValue.");$('#inputRequest').val('".$request."');$('#inputCurrency').val(".$idCurrency.");$('#price').html('".$valCurrency." ".$price."');$('#vat').html('".$valCurrency." ".$vat."');$('#total').html('".$valCurrency." ".$total."');$('#code').val('".$code."');$('#booking-data').toggle(300);</script>",
									'msg' => '',
									'type' => '');

		}else{
			$return=array('html' => "",
						'msg' => $book_updbooking_msg_incorrect_code,
						'type' => 'e');
		}
		break;

	case "updateBooking":
		$checkin=$_GET['checkin'];
		$checkout=$_GET['checkout'];
		$guests=$_GET['guests'];
		$name=$_GET['inputName'];
		$lastName=$_GET['inputLastName'];
		$idCountry=$_GET['inputCountry'];
		$email=$_GET['inputEmail'];
		$phone=$_GET['inputPhone'];
		$optPhone=$_GET['inputOptPhone'];
		$arrive=$_GET['arrive'];
		$arriveValue=$_GET['inputArrive'];
		$request=$_GET['inputRequest'];
		$idCurrency=$_GET['inputCurrency'];
		$code=$_GET['code'];
		$checkin=generalizeDate($checkin,$_SESSION['languaje']);
		$checkout=generalizeDate($checkout,$_SESSION['languaje']);

		//Calculo precios
		$pricing=calcPrice($checkin,$checkout,$guests,$idCurrency);
		$price = $pricing['price'];
    	$vat = $pricing['iva'];
    	$total = $pricing['final'];
    	$valCurrency = $pricing['currency'];

		//Calulo la cantidad de días de la reserva
		$days=cantDays(date($checkin),date($checkout));
    	    	

		try{
			sql("UPDATE `u172676809_fcac`.`T_BOOKS` SET
				`DT_CHECK_IN`=STR_TO_DATE(?,'%d-%m-%Y'),
				`DT_CHECK_OUT`=STR_TO_DATE(?,'%d-%m-%Y'),
				`INT_GUESTS`=?,
				`CHR_NAME`=?,
				`CHR_LAST_NAME`=?,
				`FK_ID_COUNTRY`=?,
				`CHR_EMAIL`=?,
				`CHR_PHONE`=?,
				`CHR_OPT_PHONE`=?,
				`CHR_ARRIVE`=?,
				`CHR_REQUEST`=?,
				`DCM_PRICE`=?,
				`DCM_VAT`=?,
				`DCM_TOTAL`=?,
				`ID_CURRENCY`=?,
				`INT_DAYS`=?,
				`INT_ARRIVE_VALUE`=?
				WHERE CHR_BOOK_CODE=CONVERT(? USING UTF8) COLLATE utf8_spanish_ci",array($checkin,$checkout,$guests,$name,$lastName,$idCountry,$email,$phone,$optPhone,$arrive,$request,$price,$vat,$total,$idCurrency,$days,$arriveValue,$code));

		}catch(exception $e){
		   	$return=array('html' => "",
						'msg' => $book_updbooking_msg_error,
						'type' => 'e');
		   	break;
		}

		/*$pos_sep = strpos($msgText, '-');
		$len_type = $pos_sep;
		$type = substr($msgText,0,$len_type);
		$len = strlen($msgText);
		$len_msg = $len - $pos_sep;
		$msg = substr($msgText,$pos_sep+1,$len_msg);*/


		$rs_book=sql("SELECT DT_EXPIRATION_DATE AS EXPIRATION FROM u172676809_fcac.T_BOOKS WHERE CHR_BOOK_CODE=?",array($code));
		while($row = siguiente($rs_book))
		   	$expDate = $row->EXPIRATION;

		$expDate = formatDateLong($expDate,'es');
		$checkin = formatDateLong($checkin,'es');
		$checkout = formatDateLong($checkout,'es');
			    
		//Enviar mail usuario
		$body = '<tr><td style="padding:5px;font-size:20px;font-family:Candara,Calibri,Arial,sans-serif;color:#FFD700;">'.$mail_dear.' '.$name.':'.'</td></tr>';
		$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_updbooking_mail_line1.'</td></tr>';
		$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_mail_line2.'</td></tr>';
		$body.= '<tr><td><table border="1" rules="all" width="80%" align="center">';
		$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_check_in.': '.$checkin.'</td><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_confirm_days.': '.$days.'</td></tr>';
		$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_check_out.': '.$checkout.'</td><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_guests.': '.$guests.'</td></tr>';
		$body.= '<tr><td colspan="2" style="padding:5px;font-size:18px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;text-align:center;">'.$book_confirm_total.': '.$valCurrency.' '.$total.'.-</td></tr>';
		$body.= '</table></td></tr>';
		$body.= '<tr><td><p style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_mail_line3.'<span style="padding:5px;font-size:22px;font-family:Candara,Calibri,Arial,sans-serif;color:#FFD700;">'.$code.'</span>'.$book_mail_line4.'.</p></td></tr>';
		$body.= '<tr><td><hr></td></tr>';
		$body.= '<tr><td style="padding:1px;font-size:10px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;"><em>'.$book_mail_foot.'</em></td></tr>';

		sendMail($email,'book',$book_updbooking_mail_subject,$body);


		//Enviar mail FCAC
		$body = '<tr><td border-style="padding:5px;font-size:20px;font-family:Candara,Calibri,Arial,sans-serif;color:#FFD700;">Se ha modificado una reserva.</td></tr>';
		sendMail('booking@firstclassapartment.com.ar','book','Modificacion de Reserva',$body);

		$return=array('html' => "<script>$('#booking-data').toggle(300);showMsg('confirmation1','".$book_updbooking_msg_conf_1."','o');showMsg('confirmation2','".$book_updbooking_msg_conf_2."','i');</script>",
						'msg' => '',
						'type' => '');

		setSysNew('i','Se ha actualizado una reserva. Código de Reserva: '.$code);

		break;

	case "cancelBooking":
		$code=$_GET['code'];
		try{
			$rs = sql("UPDATE `u172676809_fcac`.`T_BOOKS` SET
						`INT_CANCEL`=1,
						`DT_CANCEL`=CURRENT_TIMESTAMP
						WHERE CHR_BOOK_CODE=CONVERT(? USING UTF8) COLLATE utf8_spanish_ci",array($code));
		}catch(exception $e){
		   	$return=array('html' => "",
						'msg' => $book_updbooking_cancel_msg_error,
						'type' => 'e');
		   	break;
		}

		try{
			$rs_data = sql("SELECT CHR_NAME,CHR_EMAIL FROM `u172676809_fcac`.`T_BOOKS`
						WHERE CHR_BOOK_CODE=CONVERT(? USING UTF8) COLLATE utf8_spanish_ci",array($code));
			$reg=siguiente($rs_data);
			$email=$reg->CHR_EMAIL;
			$name=$reg->CHR_NAME;
		}catch(exception $e){
		   	$return=array('html' => "",
						'msg' => $book_updbooking_cancel_msg_error,
						'type' => 'e');
		   	break;
		}

		/*$pos_sep = strpos($msgText, '-');
		$len_type = $pos_sep;
		$type = substr($msgText,0,$len_type);
		$len = strlen($msgText);
		$len_msg = $len - $pos_sep;
		$msg = substr($msgText,$pos_sep+1,$len_msg);*/

		//Enviar mail
		$body = '<tr><td style="padding:5px;font-size:20px;font-family:Candara,Calibri,Arial,sans-serif;color:#FFD700;">'.$mail_dear.' '.$name.':'.'</td></tr>';
		$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_updbooking_cancel_mail_line1.'<span style="padding:5px;font-size:22px;font-family:Candara,Calibri,Arial,sans-serif;color:#FFD700;">'.$code.'</span>'.$book_updbooking_cancel_mail_line2.'</td></tr>';
		$body.= '<tr><td style="padding:5px;font-size:15px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;">'.$book_updbooking_cancel_mail_line3.'</td></tr>';
		$body.= '<tr><td><hr></td></tr>';
		$body.= '<tr><td style="padding:1px;font-size:10px;font-family:Candara,Calibri,Arial,sans-serif;color:#CECECE;"><em>'.$book_mail_foot.'</em></td></tr>';
		//$body='test';
		//var_dump($email);
		sendMail($email,'book',$book_updbooking_cancel_mail_subject,$body);

		//Enviar mail FCAC
		$body = '<tr><td border-style="padding:5px;font-size:20px;font-family:Candara,Calibri,Arial,sans-serif;color:#FFD700;">Se ha cancelado una reserva.</td></tr>';
		sendMail('booking@firstclassapartment.com.ar','book','Cancelacion de Reserva',$body);

		$return=array('html' => "<script>$('#booking-data').toggle(300);</script>",
						'msg' => $book_updbooking_cancel_mail_line1.$code.$book_updbooking_cancel_mail_line2,
						'type' => 'o');
		
		setSysNew('w','Se ha cancelado una reserva. Código de Reserva: '.$code);

		break;

	case 'listArchivos':
		$path=$_GET['path'];
		$return=listarArchivos($path);
		//var_dump($return);
		break;
}

echo json_encode($return);
exit;